<template>
  <div class="audit-pending">
    <div class="page-header">
      <h2>待审核项目</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="项目类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择项目类型"
            clearable
          >
            <el-option label="纵向课题" value="vertical" />
            <el-option label="横向课题" value="horizontal" />
            <el-option label="学术论文" value="paper" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入项目名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="提交人">
          <el-input
            v-model="searchForm.submitter"
            placeholder="请输入提交人"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="项目名称" min-width="200" />
        <el-table-column prop="type" label="项目类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitterName" label="提交人" width="120" />
        <el-table-column prop="submitterDepartment" label="所属院系" width="150" />
        <el-table-column prop="submitTime" label="提交时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag type="warning">
              待审核
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">
              查看详情
            </el-button>
            <el-button type="text" @click="handleApprove(row)">
              通过
            </el-button>
            <el-button
              type="text"
              @click="handleReject(row)"
              style="color: #f56c6c"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditType === 'approve' ? '审核通过' : '审核拒绝'"
      width="500px"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="审核意见" prop="comment">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="4"
            :placeholder="auditType === 'approve' ? '请输入审核通过的意见（可选）' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirmAudit"
          :loading="auditing"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="项目详情"
      width="800px"
    >
      <div v-if="currentItem" class="item-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称" :span="2">
            {{ currentItem.title }}
          </el-descriptions-item>
          <el-descriptions-item label="项目类型">
            <el-tag :type="getTypeTagType(currentItem.type)">
              {{ getTypeText(currentItem.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交人">
            {{ currentItem.submitterName }}
          </el-descriptions-item>
          <el-descriptions-item label="所属院系">
            {{ currentItem.submitterDepartment }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ formatDate(currentItem.submitTime) }}
          </el-descriptions-item>
          <!-- 根据类型显示不同的详细信息 -->
          <template v-if="currentItem.type === 'vertical'">
            <el-descriptions-item label="项目级别">
              {{ currentItem.projectLevel }}
            </el-descriptions-item>
            <el-descriptions-item label="总金额">
              {{ currentItem.totalAmount }}万元
            </el-descriptions-item>
            <el-descriptions-item label="批准部门">
              {{ currentItem.approvalDepartment }}
            </el-descriptions-item>
            <el-descriptions-item label="项目负责人">
              {{ currentItem.projectLeader }}
            </el-descriptions-item>
          </template>
          <template v-else-if="currentItem.type === 'horizontal'">
            <el-descriptions-item label="合同金额">
              {{ currentItem.contractAmount }}万元
            </el-descriptions-item>
            <el-descriptions-item label="甲方单位">
              {{ currentItem.partyAName }}
            </el-descriptions-item>
            <el-descriptions-item label="项目负责人">
              {{ currentItem.projectLeader }}
            </el-descriptions-item>
            <el-descriptions-item label="执行负责人">
              {{ currentItem.executionLeader }}
            </el-descriptions-item>
          </template>
          <template v-else-if="currentItem.type === 'paper'">
            <el-descriptions-item label="期刊">
              {{ currentItem.journal }}
            </el-descriptions-item>
            <el-descriptions-item label="检索级别">
              {{ currentItem.indexLevel }}
            </el-descriptions-item>
            <el-descriptions-item label="第一作者">
              {{ currentItem.firstAuthor }}
            </el-descriptions-item>
            <el-descriptions-item label="通讯作者">
              {{ currentItem.correspondingAuthor }}
            </el-descriptions-item>
          </template>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { auditAPI } from '@/api/audit'

export default {
  name: 'AuditPending',
  components: {
    Search,
    Refresh
  },
  setup() {
    const loading = ref(false)
    const auditing = ref(false)
    const tableData = ref([])
    const auditDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const currentItem = ref(null)
    const auditType = ref('approve')
    const auditFormRef = ref()

    const searchForm = reactive({
      type: '',
      title: '',
      submitter: ''
    })

    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    const auditForm = reactive({
      comment: ''
    })

    const auditRules = reactive({
      comment: [
        {
          validator: (rule, value, callback) => {
            if (auditType.value === 'reject' && !value) {
              callback(new Error('拒绝时必须填写拒绝原因'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    })

    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.currentPage - 1,
          size: pagination.pageSize,
          status: 'PENDING',
          ...searchForm
        }

        const response = await auditAPI.getPendingItems(params)
        tableData.value = response.data || []
        pagination.total = response.data ? response.data.length : 0
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      loadData()
    }

    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.currentPage = 1
      loadData()
    }

    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadData()
    }

    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadData()
    }

    const handleView = (row) => {
      currentItem.value = row
      detailDialogVisible.value = true
    }

    const handleApprove = (row) => {
      currentItem.value = row
      auditType.value = 'approve'
      auditForm.comment = ''
      auditDialogVisible.value = true
    }

    const handleReject = (row) => {
      currentItem.value = row
      auditType.value = 'reject'
      auditForm.comment = ''
      auditDialogVisible.value = true
    }

    const handleConfirmAudit = async () => {
      try {
        await auditFormRef.value.validate()

        auditing.value = true

        // 将前端的类型映射为后端的成果类型
        const achievementTypeMap = {
          'vertical': 1,    // 纵向课题
          'horizontal': 2,  // 横向课题
          'paper': 3        // 学术论文
        }

        const achievementType = achievementTypeMap[currentItem.value.type]
        const achievementId = currentItem.value.id
        const comment = auditForm.comment || ''

        if (auditType.value === 'approve') {
          await auditAPI.approve(achievementType, achievementId, comment)
        } else {
          await auditAPI.reject(achievementType, achievementId, comment)
        }

        ElMessage.success(auditType.value === 'approve' ? '审核通过' : '审核拒绝')
        auditDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核失败')
      } finally {
        auditing.value = false
      }
    }

    const getTypeText = (type) => {
      const typeMap = {
        vertical: '纵向课题',
        horizontal: '横向课题',
        paper: '学术论文'
      }
      return typeMap[type] || '未知类型'
    }

    const getTypeTagType = (type) => {
      const typeMap = {
        vertical: 'primary',
        horizontal: 'success',
        paper: 'warning'
      }
      return typeMap[type] || 'info'
    }

    const formatDate = (date) => {
      if (!date) return '-'
      return new Date(date).toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadData()
    })

    return {
      loading,
      auditing,
      tableData,
      searchForm,
      pagination,
      auditDialogVisible,
      detailDialogVisible,
      currentItem,
      auditType,
      auditForm,
      auditRules,
      auditFormRef,
      loadData,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      handleApprove,
      handleReject,
      handleConfirmAudit,
      getTypeText,
      getTypeTagType,
      formatDate
    }
  }
}
</script>

<style lang="scss" scoped>
.audit-pending {
  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }

  .item-detail {
    .el-descriptions {
      margin-top: 20px;
    }
  }
}
</style>
